from django.contrib.auth import get_user_model, authenticate
from django.contrib.auth.models import AnonymousUser
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from utils.django.password_validate import password_validate
from .fields import PasswordField

User = get_user_model()
USERNAME_FIELD = User.USERNAME_FIELD


class ResetSelfPasswordSerializer(serializers.Serializer):
    old_password = PasswordField(required=True)
    new_password = PasswordField(required=True)

    def __init__(self, *args, **kwargs):
        self.user = None
        super().__init__(*args, **kwargs)

    def validate_new_password(self, value):
        password_validate(value)
        return value

    def validate(self, attrs):
        self.user = self.context['request'].user
        # 登陆凭证验证
        credentials = {
            USERNAME_FIELD: getattr(self.user, USERNAME_FIELD),
            'password': attrs.get('old_password')
        }
        user = authenticate(**credentials)
        if not user:
            raise serializers.ValidationError('旧密码输入错误')
        return attrs

    def save(self, **kwargs):
        self.user.set_password(self.validated_data['new_password'])
        self.user.save()
        return self.user


class ResetOtherPasswordSerializer(serializers.Serializer):
    user_id = serializers.IntegerField(required=True)
    new_password = PasswordField(required=True)

    def __init__(self, *args, **kwargs):
        self.user = None
        super().__init__(*args, **kwargs)

    def validate_new_password(self, value):
        password_validate(value)
        return value

    def validate(self, attrs):
        try:
            self.user = User.objects.filter(id=attrs['user_id']).first()
        except Exception as e:
            raise ValidationError('"user_id"字段输入有误')
        return attrs

    def save(self, **kwargs):
        self.user.set_password(self.validated_data['new_password'])
        self.user.save()
        return self.user
